<div class="page-title">
    <a id="button-user-create" href="javascript:void(0);"><i class="fa fa-plus"></i>新增用户</a>
    <a id="button-user-update" href="javascript:void(0);"><i class="fa fa-pencil-square-o"></i>修改用户</a>
    <a id="button-user-torole" href="javascript:void(0);"><i class="fa fa-users"></i>修改角色</a>
</div>
<div class="panel-box">    
    <div class="page-title">
        <form class="filter-search" style="width: 400px;">
            <input id="filter_account" type="text" placeholder="账号/用户名" style="width: 350px;">
            <i id="filter-user-qrybtn" class="fa fa-search"></i>
        </form>
    </div>
    <div class="table-responsive">
        <table id="table-user-sheet" class="table table-hover" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th></th>
                    <th>用户ID</th>
                    <th>用户账号</th>
                    <th>用户名称</th>
                    <th>状 态</th>
                    <th>角 色</th>
                    <th>手机号码</th>
                    <th>邮箱地址</th>
                    <th>微信账号</th>
                    <th>创建时间</th>
                    <th>备注描述</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>
<div id="dialog-user-update" class="modal fade" tabindex="-1" data-width="550" data-backdrop="static" data-keyboard="false" style="display: none;"> 
    <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
        <h4 id="dtitle-user-update" class="modal-title">修改用户</h4> 
    </div>
    <div class="modal-body"> 
        <form id="form-user-update" class="m-t form-horizontal" role="form"> 
            <input  name="memberid" type="hidden">
            <div class="form-group">
                <label class="col-lg-2 control-label">用户账号</label>
                <div class="col-lg-10"><input  name="account" placeholder="用户账号" class="form-control" maxlength="32" required  data-error="用户账号不能为空"><div class="help-block with-errors"></div></div>
            </div>
            <div id="form-gfield-password" class="form-group">
                <label class="col-lg-2 control-label">用户密码</label>
                <div class="col-lg-10"><input name="password" type="password" placeholder="用户密码" class="form-control" pattern="^\w{4,32}$" required  data-error="密码长度不能小于4位"><div class="help-block with-errors"></div></div>
            </div>
            <div class="form-group">
                <label class="col-lg-2 control-label">用户名称</label>
                <div class="col-lg-10"><input name="membername" placeholder="用户名称" class="form-control" maxlength="32" required  data-error="用户名称不能为空"><div class="help-block with-errors"></div></div>
            </div>
            <br>
            <div class="form-group">
                <label class="col-lg-2 control-label">手 机</label>
                <div class="col-lg-10"><input name="mobile" type="tel" placeholder="手 机" class="form-control"></div>
            </div>
            <div class="form-group">
                <label class="col-lg-2 control-label">邮 箱</label>
                <div class="col-lg-10"><input name="email" type="email" placeholder="邮 箱" class="form-control"></div>
            </div>
            <div class="form-group">
                <label class="col-lg-2 control-label">微信账号</label>
                <div class="col-lg-10"><input name="weixin" placeholder="微信账号" class="form-control"></div>
            </div>
            <div class="form-group">
                <label class="col-lg-2 control-label">备注说明</label>
                <div class="col-lg-10"><textarea name="remark" placeholder="备注说明" style="height: 8rem;" class="form-control"></textarea></div>
            </div>
            <br>
            <button id="formbtn-user-update" type="button" class="btn btn-theme btn-lg btn-block ">提 交</button><br> 
        </form> 
    </div> 
    <div id="tips-user-update" class="module-alert-tips"></div><br>  
</div>

<div id="dialog-user-torole" class="modal fade" tabindex="-1" data-width="400" style="display: none;"> 
    <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
        <h4 id="dtitle-user-torole" class="modal-title">修改角色</h4> 
    </div>
    <div class="modal-body"> 
        <form id="form-user-torole" class="m-t form-horizontal" role="form"> 
            <input  name="memberid" type="hidden">
            <input  name="oldroleids" type="hidden">
            <div id="fdiv-user-roleboxes">
                <div class="form-group">
                    <label class="col-lg-2 control-label" for="xxxx_20160225" style="margin-top: -5px;width: 50%;">普通角色</label><input id="xxxx_20160225" type="checkbox" name="roleid_1001" value="1001"/>
                </div>
            </div>
            <br>
            <button id="formbtn-user-torole" type="button" class="btn btn-theme btn-lg btn-block ">提 交</button><br> 
        </form> 
    </div> 
    <div id="tips-user-torole" class="module-alert-tips"></div><br>  
</div>

<script>
    {
        if (system_memberinfo && system_memberinfo.memberid) {
            $.ajax({
                dataType: "json",
                url: '/pipes/role/query',
                success: function (sheetdata) {
                    var rolerows = sheetdata.rows || [];
                    var allroledata = {};
                    var divroleboxhtml = [];
                    var roleprefix = "role_" + new Date().getTime() + "_";
                    for (var i = 0; i < rolerows.length; i++) {
                        var role = rolerows[i];
                        allroledata["" + role.roleid] = rolerows[i].rolename;
                        var elrid = roleprefix + role.roleid;
                        divroleboxhtml.push('<div class="form-group">');
                        divroleboxhtml.push('   <label class="col-lg-2 control-label" for="' + elrid + '" style="margin-top: -5px;width: 50%;">' + role.rolename + '</label>');
                        divroleboxhtml.push('   <input name="roleid_' + role.roleid + '" id="' + elrid + '" type="checkbox" value="' + role.roleid + '"/>');
                        divroleboxhtml.push('</div>');
                    }
                    $('#fdiv-user-roleboxes').html(divroleboxhtml.join(''));
                    //----------------------------------------------------
                    var mtable = $('#table-user-sheet').dataTable({
                        ajax: {
                            url: "/pipes/user/query",
                            data: function (f) {
                                f.bean = JSON.stringify({
                                    account: $('#filter_account').val().trim(),
                                    membername: $('#filter_account').val().trim()
                                });
                                f.sort = 'memberid';
                                f.order = 'DESC';
                            },
                        },
                        columnDefs: [{
                                className: 'select-checkbox',
                                targets: 0
                            }],
                        columns: [
                            {"data": "", render: $.defrender},
                            {"data": "memberid", render: $.defrender},
                            {"data": "account", render: $.defrender},
                            {"data": "membername", render: $.defrender},
                            {"data": "status", render: defStatusRender},
                            {"data": "roleids", render: function (value, type, full) {
                                    if (!value || !value.length) return "";
                                    var a = [];
                                    for (var i = 0; i < value.length; i++) {
                                        var n = allroledata["" + value[i]];
                                        a.push(n ? n : value[i]);
                                    }
                                    return a.join("  ");
                                }},
                            {"data": "mobile", render: $.defrender},
                            {"data": "email", render: $.defrender},
                            {"data": "weixin", render: $.defrender},
                            {"data": "createtime", render: Date.DateFormatter},
                            {"data": "remark", render: $.defrender}
                        ]
                    });

                    $('#filter-user-qrybtn').bind("click", function () {
                        mtable.api(true).draw(false);
                    });
                    //--------------------------- 初始化修改用户 -----------------------------
                    $('#button-user-create').bind("click", function () {
                        $('#form-gfield-password').show();
                        $('#dtitle-user-update').html("新增用户");
                        $("#tips-user-update").html('');

                        $("#form-user-update").form('reset');
                        $('#dialog-user-update').modal('show');
                    });
                    $('#button-user-update').bind("click", function () {
                        var data = mtable.api(true).row({selected: true}).data();
                        if (!data || !data.memberid) {
                            alert("请选择一条记录！");
                            return;
                        }
                        if (data.type == system_adminpid) {
                            alert("不允许修改管理员账号");
                            return;
                        }
                        $('#form-gfield-password').hide();
                        $('#dtitle-user-update').html("修改用户");
                        $("#tips-user-update").html('');
                        $("#form-user-update").form('reset');
                        $("#form-user-update").form('load', data);
                        $('#dialog-user-update').modal('show');
                    });
                    //------------------------ 新增&修改用户 -----------------------------                
                    $('#formbtn-user-update').bind("click", function (e) {
                        var form = $("#form-user-update");
                       
                        var json = form.serializeJson();
                        $.ajax({
                            cache: false,
                            dataType: "json",
                            type: "POST",
                            url: json.memberid ? '/pipes/user/update' : '/pipes/user/create',
                            data: {
                                "bean": $.objectToString(json),
                            },
                            error: function () {//请求失败处理函数
                                alert('请求失败');
                            },
                            success: function (data) {
                                $("#dialog-user-update").modal('hide');
                                mtable.api(true).draw(false);
                            }
                        });
                    });

                    //------------------------ 修改角色列表 ----------------------------- 
                    $('#button-user-torole').bind("click", function () {
                        var data = mtable.api(true).row({selected: true}).data();
                        if (!data || !data.memberid) {
                            alert("请选择一条记录！");
                            return;
                        }
                        if (data.type == system_adminpid) {
                            alert("不允许修改管理员账号");
                            return;
                        }
                        $("#tips-user-torole").html('');
                        $("#form-user-torole").form('reset');
                        $("#form-user-torole").form('load', {memberid: data.memberid, oldroleids: (data.roleids || []).join(',')});
                        var roleidstr = ',' + (data.roleids || []).join(',') + ',';
                        for (var i = 0; i < rolerows.length; i++) {
                            var role = rolerows[i];
                            var elrid = roleprefix + role.roleid;
                            document.getElementById(elrid).checked = roleidstr.indexOf(',' + role.roleid + ',') >= 0;
                        }
                        $('#dialog-user-torole').modal('show');
                    });
                    //------------------------- 修改角色 -------------------------------                
                    $('#formbtn-user-torole').bind("click", function (e) {
                        var form = $("#form-user-torole");
                        if (!form.form('validate')) return;
                        var json = form.serializeJson();

                        var oldobjs = {};
                        if (json.oldroleids) {
                            $.each(json.oldroleids.split(','), function (i, v) {
                                if (v) oldobjs['' + v] = 1;
                            });
                        }

                        var delroleids = [];
                        var newuseroles = [];
                        for (var p in json) {
                            if (p.indexOf("roleid_") < 0) continue;
                            if (oldobjs[json[p]]) {
                                delete oldobjs[json[p]];
                                continue;
                            }
                            newuseroles.push({memberid: json.memberid, roleid: json[p]});
                        }
                        for (var k in oldobjs) {
                            delroleids.push(k);
                        }

                        $.ajax({
                            cache: false,
                            dataType: "json",
                            type: "POST",
                            url: '/pipes/role/upduserole',
                            data: {
                                "delmemberid": delroleids.length ? json.memberid : 0,
                                "delroleids": $.objectToString(delroleids),
                                "bean": $.objectToString(newuseroles),
                            },
                            error: function () {//请求失败处理函数
                                alert('请求失败');
                            },
                            success: function (data) {
                                $("#dialog-user-torole").modal('hide');
                                mtable.api(true).draw(false);
                            }
                        });
                    });
                    //--------------------------------------------------------------------------
                },
                error: function () {
                    alert('获取角色信息失败');
                }
            });
        }
    }
</script>
